<template>
  <div class="roles">
    <!-- 目录导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="roleId" placeholder="请输入内容" @input="getRolesList">
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button size="medium" type="primary" icon="el-icon-plus"
            @click="openDialog('add')">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bd-bottom', index1 === 0 ? 'bd-top':'', 'vcenter']"
              v-for="(item1, index1) in scope.row.children" :key="index1">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag size="mini" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二和三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row :class="[index2 === 0 ? '':'bd-top', 'vcenter']"
                  v-for="(item2, index2) in item1.children" :key="index2">
                  <el-col :span="6">
                    <el-tag size="mini" type="success" closable>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag size="mini" type="warning" closable
                      @close="removeAuthByID(scope.row, item3.id)"
                      v-for="(item3, index3) in item2.children" :key="index3">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="id" label="角色ID"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="operation" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-edit" @click="openDialog('edit', scope.row)"></el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="delConfirmMsg(scope.row)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="small" icon="el-icon-setting" @click="openDialog('setRight', scope.row)"></el-button>
            </el-tooltip> 
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%" @close="dialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" v-if="addFormConfig.isForm">
        <el-form-item prop="roleName">
          <el-input prefix-icon="el-icon-user" v-model="addForm.roleName"
            placeholder="请输入角色名称">
          </el-input>
        </el-form-item>
        <el-form-item prop="roleName">
          <el-input prefix-icon="el-icon-edit-outline" v-model="addForm.roleDesc"
            placeholder="请输入角色描述">
          </el-input>
        </el-form-item>
      </el-form>
      <el-tree  v-else
        ref="elTreeRef"
        :data="rolesRights" 
        show-checkbox 
        :props="defaultProps"
        node-key="id"
        :default-expanded-keys="defaultKeys" 
        :default-checked-keys="defaultKeys">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="medium" @click="submitFormData(addFormConfig.option)">确定</el-button>
        <el-button size="medium" type="danger" @click="resetFormData">重置</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 定义角色id
      roleId: '',
      roleIdCopy: '',
      // 定义角色列表
      rolesList: [],
      // 角色权限列表
      rolesRights: [],
      // 定义用户权限树的显示
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      // 定义表单数据，验证规则，表单配置
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      addFormConfig: {
        option: 'add',//当前表单操作
        isForm: true
      },
      // 定义都dialog的配置
      dialogVisible: false,
      dialogTitle: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      let url = this.roleId ? `roles/${this.roleId}`:'roles'
      //console.log(url)
      
      const {data: res} = await this.$axios.get(url)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //this.$message({message: res.meta.msg, type: 'success'})

      if(res.data instanceof Array) {
        this.rolesList = res.data
      }else {
        let temp = []
        if (!res.data.hasOwnProperty('id')) res.data.id = res.data.roleId
        temp.push(res.data)
        this.rolesList = temp
      }
    },
    // 删除权限
    async removeAuthByID(role, rightsId) {
      console.log(role.id + " " + rightsId)
      const confirmResult = await this.$confirm('此操作将删除该角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        // this.$message({type: 'info', message: '已取消删除'})         
      })
      if (confirmResult !== 'confirm') {
        return this.$message({type: 'info', message: '已取消删除'})
      }
      const {data: res} = await this.$axios.delete(`roles/${role.id}/rights/${rightsId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message({message: res.meta.msg, type: 'success'})
      // 为当前角色权限重新赋值
      role.children = res.data
    },
    // 打开用户对话框
    openDialog(option, data) {
      this.dialogVisible = !this.dialogVisible
      this.addFormConfig.option = option
      switch (option) {
        case 'add':
          console.log(option + '添加角色');
          this.dialogTitle = '添加角色'
          this.addFormConfig.isForm = true
          break;
        case 'edit':
          console.log(option + '编辑角色信息', data);
          this.dialogTitle = '编辑角色信息'
          this.addFormConfig.isForm = true
          this.roleIdCopy = data.id
          this.addForm.roleName = data.roleName
          this.addForm.roleDesc = data.roleDesc
          break;
        case 'setRight':
          console.log(option + '分配角色权限');
          this.dialogTitle = '分配角色权限'
          this.addFormConfig.isForm = false
          this.roleIdCopy = data.id
          this.getAllRolesRights()
          // console.log(data);

          this.defaultKeys = []
          this.getRoleCurrentRights(data, this.defaultKeys)
          break;
      }
    },
    // 监听对话框关闭事件
    dialogClose() {
      this.roleId = ''
      this.defaultKeys = []
      this.addForm.roleName = ''
      this.addForm.roleDesc = ''
      if (this.addFormConfig.isForm) {
        this.$refs.addFormRef.resetFields()
      }
    },
    // 提交表单数据
    submitFormData(option) {
      console.log('option: ' + option)
      // 发送请求
      switch (option) {
        case 'add':
          this.$refs.addFormRef.validate(async valid => {
            if (!valid) return
            const { data: res } = await this.$axios.post('roles', this.addForm)
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
            } else {
              this.$message({message: res.meta.msg, type: 'success'})
              this.getRolesList()
              this.dialogVisible = !this.dialogVisible
            }
          })
          break;
        case 'edit':
          console.log('发送修改数据的请求', this.addForm);
          this.$axios.put(`roles/${this.roleIdCopy}`, this.addForm).then(
            (res) => {
              if (res.data.meta.status !== 200) {
                this.$message.error(res.data.meta.msg)
              } else {
                this.$message({message: '修改成功', type: 'success'})
                this.getRolesList()
                this.dialogVisible = !this.dialogVisible
              }
            }
          )
          break;
        case 'setRight':
          console.log('发送修改权限数据的请求',
            [...this.$refs.elTreeRef.getCheckedKeys(),
            ...this.$refs.elTreeRef.getHalfCheckedKeys()]
          )
          this.setRoleCurrentRights()
          break;
      }
    },
    // 重置表单数据
    resetFormData() {
      this.$refs.addFormRef.resetFields()
    },
    // 打开删除确认框
    delConfirmMsg(userInfo) {
      this.$confirm('此操作将删除该角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${userInfo.id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({type: 'success', message: res.meta.msg})
        this.getRolesList()
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除'})   
      })
    },
    // 获取角色所有权限列表
    async getAllRolesRights() {
      const {data: res} = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesRights = res.data
    },
    // 递归获取当前角色权限
    getRoleCurrentRights(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getRoleCurrentRights(item, arr)
      })
    },
    // 设置当前角色的权限
    async setRoleCurrentRights() {
      const keys = [
        ...this.$refs.elTreeRef.getCheckedKeys(),
        ...this.$refs.elTreeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data: res} = await this.$axios.post(`roles/${this.roleIdCopy}/rights`, {rids: idStr})
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message({message: res.meta.msg, type: 'success'})
      this.roleIdCopy = ''
      this.getRolesList()
      this.dialogVisible = !this.dialogVisible
    }
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tree {
  max-height: 130px;
  overflow-y: scroll;
}
</style>